local ChannelBase = import(".ChannelBase")
local ChannelEmaOversea = class("ChannelEmaOversea", ChannelBase)


function ChannelEmaOversea:ctor()
    self.super.ctor(self)
    self._loginParams = {}
    self._timeDt = 0
    self._tempCurTime = 0
    self._initSdkState = -1
    self._isFirstShowLogin = true
    -- self._tempMyServers = {}
end

function ChannelEmaOversea:getAccount()
    if self._loginParams and self._loginParams.account then
        return self._loginParams.account
    end
    return ""
end

function ChannelEmaOversea:_init()
    app:addCustomEventListener("CHANNEL_LOGIN_EVENT", function(event)
		local param = event:getUserStr()
		self:loginCallback(param)
    end)
    
    app:addCustomEventListener("CHANNEL_MYSERVER_EVENT", function(event)
		local param = event:getUserStr()
		self:myServersCallback(param)
    end)
    
    app:addCustomEventListener("CHANNEL_NEWSERVER_EVENT", function(event)
		local param = event:getUserStr()
		self:newServersCallback(param)
    end)

    app:addCustomEventListener("CHANNEL_FETCH_SERVER_EVENT", function(event)
		local param = event:getUserStr()
		self:fetchServersCallback(param)
    end)

    app:addCustomEventListener("CHANNEL_TIME_EVENT", function(event)
        local param = event:getUserStr()
        local t = tonumber(param)
        if t then
            self._timeDt = t - self._tempCurTime
        end
    end)
    
    app:addCustomEventListener("CHANNEL_SWITCH_ACCOUT_EVENT", function(event)
		local param = event:getUserStr()
		self:switchAccoutCallback(param)
    end)

    app:addCustomEventListener("CHANNEL_PAY_EVENT", function(event)
		local param = event:getUserStr()
		self:payCallback(param)
    end)

    -- app:addCustomEventListener("CHANNEL_INIT_EVENT", function(event)
	-- 	local param = event:getUserStr()
	-- 	self:initCallback(param)
    -- end)

    app:addCustomEventListener("CHANNEL_UPGRADE_ACCOUNT_EVENT", function(event)
		local param = event:getUserStr()
		self:accountUpgradeCallback(param)
    end)
    
    app:addCustomEventListener("CHANNEL_FORCE_LOGOUT_EVENT", function(event)
		local param = event:getUserStr()
		self:forceLogoutCallback(param)
    end)

    app:addCustomEventListener("CHANNEL_PRODUCT_LIST_EVENT", function(event)
		local param = event:getUserStr()
		self:getProductListCallback(param)
    end)

    app:addCustomEventListener("CHANNEL_GIFT_CODE_EVENT", function(event)
		local param = event:getUserStr()
		self:checkGiftCodeCallback(param)
    end)

    app:addCustomEventListener("CHANNEL_GIFT_CODE_EVENT", function(event)
		local param = event:getUserStr()
		self:checkGiftCodeCallback(param)
    end)
    
end


function ChannelEmaOversea:getChannelTag()
	return app:getChannelTag()
end

function ChannelEmaOversea:getChannelId()
	return "ema"
end


function ChannelEmaOversea:_login()
    self._isCallLogin = true
    if self._isFirstShowLogin then
        self._isFirstShowLogin = false
        scheduler.newCron(function()
            if not self:isLogin() then
                self:showLoginView()
            end
        end, 2, false)

        -- 新sdk
        scheduler.newCron(function()
            if app:isAndroid() then
                self.callJava("()V", "login")
            elseif app:isIOS() then
                self.callOC("login")
            end
        end, 0.5, false)
    else
        self:showLoginView()
        if app:isAndroid() then
            self.callJava("()V", "login")
        elseif app:isIOS() then
            self.callOC("login")
        end
    end
end

function ChannelEmaOversea:_logout(params)
    scheduler.newCron(function()
        if app:isAndroid() then
            self.callJava("()V", "switchAccount")
        elseif app:isIOS() then
            self.callOC("logout")
        end
    end, 0.5, false)
    
end

function ChannelEmaOversea:_switchAccount(params)
    scheduler.newCron(function()
        if app:isAndroid() then
            self.callJava("()V", "switchAccount")
        elseif app:isIOS() then
            self.callOC("logout")
        end
    end, 0.5, false)
end

function ChannelEmaOversea:_pay(payData)
    local params = {
        server_id = tostring(app.session:getZoneId()),
        quantity = "1",
        product_id = payData.product_id,
        role_id = UD.player.uid,
        custom_data = "",
        is_consume = "true",
    }
    if app:isAndroid() then
        local jstr = json.encode(params)
        self.callJava("(Ljava/lang/String;)V", "pay", jstr)
    elseif app:isIOS() then
        self.callOC("pay", params)
    end
end

function ChannelEmaOversea:_share(tp, title, desc, imagePath)
    local ok, ret
    local params = {
        imagePath = imagePath,
        text = desc,
        title = title,
        type = tp
    }
    if app:isAndroid() then
        local jstr = json.encode(params)
        ok, ret = self.callJava("(Ljava/lang/String;)V", "share", jstr)
    elseif app:isIOS() then

        params.type = params.type - 1
        ok, ret = self.callOC("share", params)
    end
end

function ChannelEmaOversea:getOpId()
    local ok, ret
    if app:isAndroid() then
        ok, ret = self.callJava("()I", "getOpId")
    elseif app:isIOS() then
        ok, ret = self.callOC("getOpId")
    end
    print("==========>>> getOpId ", ret)
    return ret
end


function ChannelEmaOversea:fetchMyServers()
    local ok
 
    local columns = "server_id|server_name|server_url2|server_port2|socket_domain2|socket_port2|first_opentime|status|utc"
    if app:isAndroid() then
        ok = self.callJava("(Ljava/lang/String;)V", "fetchMyServers", columns)
    elseif app:isIOS() then
        self.callOC("fetchMyServers", {columns = columns})
    end
    print("==========>>> fetchMyServers ", ok)
    
end

function ChannelEmaOversea:fetchNewServers()
    local ok
    local columns = "server_id|server_name|server_url2|server_port2|socket_domain2|socket_port2|first_opentime|status|utc"
    if app:isAndroid() then
        ok = self.callJava("(Ljava/lang/String;)V", "fetchNewServers", columns)
    elseif app:isIOS() then
        self.callOC("fetchNewServers", {columns = columns})
    end
    print("==========>>> fetchNewServers ", ok)
   
end


function ChannelEmaOversea:fetchServerList(cb)
    if self:isReview() and app:isIOS() then
        self._fetchReviewServerList = cb
        self:fetchReviewServerList()
    else
        self._fetchListCallBack = cb
        self:fetchMyServers()
    end
    
end


function ChannelBase:fetchReviewServerList()
    local ok
    local columns = "server_id|server_name|server_url2|server_port2|socket_domain2|socket_port2|first_opentime|status|utc"
    if app:isAndroid() then
    elseif app:isIOS() then
        -- type
        -- EMAGameServerTypeAutomatic, // 根据ip是否在白名单列表中来获取的数据，如果在则获取测试服数据，否则获取线上服
        -- EMAGameServerTypeTest,      // 测服
        -- EMAGameServerTypeReview,    // 提审
        -- EMAGameServerTypeRelease,   // 线上
        local params = {
            server_id = "",
            utc = "99",
            columns = columns,
            type = 2,
            pageNumber = 1,
            limit = "10",
        }
        ok = self.callOC("fetchServers", params)
    end
end

function ChannelBase:fetchServerListByPageNum(cb, pageNum, ibegin, iend, utc, server_id)
    local ok
    local limit = "10"
    if server_id then
        self._fetchSingleServerListByServerIdCb = cb
    else
        self._fetchServerListByPageNumCb = cb
    end
    server_id = tostring(server_id or "")

    pageNum = tostring(pageNum)

    local columns = "server_id|server_name|server_url2|server_port2|socket_domain2|socket_port2|first_opentime|status|utc"
    if app:isAndroid() then
        ok = self.callJava("(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", "fetchServers", server_id or "", utc or "99", columns, pageNum, limit)
    elseif app:isIOS() then
        -- type
        -- EMAGameServerTypeAutomatic, // 根据ip是否在白名单列表中来获取的数据，如果在则获取测试服数据，否则获取线上服
        -- EMAGameServerTypeTest,      // 测服
        -- EMAGameServerTypeReview,    // 提审
        -- EMAGameServerTypeRelease,   // 线上
        local tp = 0

        if self:isReview() then
            tp = 2
        end
        
        local params = {
            server_id = server_id or "",
            utc = utc or "99",
            columns = columns,
            type = tp,
            pageNumber = pageNum,
            limit = limit,
        }
        ok = self.callOC("fetchServers", params)
    end
    print("==========>>> fetchServerListByPageNum ", ok)
	
end


function ChannelEmaOversea:_joinUrl(host)
    local channelId = self:getChannelId()
    local channelTag = self:getChannelTag()
    local token = self._loginParams.accessToken
    local opid = self:getOpId()
    local account = self._loginParams.account
  
    if account == nil then
        local loginParamsStr
        if self._loginParams then
            loginParamsStr = json.encode(self._loginParams)
        end
        loginParamsStr = loginParamsStr or ""
        assert(false,"getAccount nil "..loginParamsStr)
    end
    

    local url = host.."gamelogin?".."channel="..channelId

    if channelTag then
        url = url.."&channeltag="..channelTag
    end

    if opid then
        url = url.."&op_id="..opid
    end

    if token then
        url = url.."&token="..token
    end
   
    if account then
        url = url.."&account="..account
    end
    print("---------------test ChannelEmaOversea:jointUrl()",url)

    return url
end

function ChannelEmaOversea:gameLogin(cb, zoneData)
    assert(zoneData ~= nil, "zoneData is nil")
    assert(zoneData.gatehost ~= nil, "zoneData is nil")
    -- local gateHost = self:getGateHost()
    self._cacheZoneData = zoneData
    self._cacheGameLoginCb = cb
    self:fetchServerListByPageNum(function(obj)
        if obj and obj.data then
            -- 区服维护
            local sdkGameStatus = tonumber(self:getGameServerStatus() or "-1")
            print("=============+>> sdkGameStatus", sdkGameStatus)
            if sdkGameStatus ~=1  then
                if obj.game_status and tonumber(obj.game_status) == Enums.AllServerStatus.Maintain then
                    local messageBox = display.newMessageBox(L("tips_3000407"),function()
                    end)
                    cc.Director:getInstance():getRunningScene():addChild(messageBox, 1000)
                    return
                end
            end
            -- 覆盖
            local singleServer = obj.data[1]
            if singleServer then
                singleServer = self:_converServerFormat(singleServer)
                for k ,v in pairs(singleServer) do
                    zoneData[k] = v
                end
            end
        end
        local sdkTime = self:getSdkTime()
        if sdkTime and zoneData.first_opentime then
            if zoneData.first_opentime > sdkTime then
                local utc = zoneData.utc
                local dateStr = ""
                if utc == "UTC+08:00" then
                    local t = zoneData.first_opentime + 8 * 60 * 60
                    dateStr = os.date("!%Y-%m-%d %H:%M", t)
                elseif utc == "UTC-05:00" then
                    local t = zoneData.first_opentime - 5 * 60 * 60
                    dateStr = os.date("!%Y-%m-%d %H:%M", t)
                elseif utc == "UTC+01:00" then
                    local t = zoneData.first_opentime + 1 * 60 * 60
                    dateStr = os.date("!%Y-%m-%d %H:%M", t)
                else
                    utc = ""
                    dateStr = os.date("%Y-%m-%d %H:%M", zoneData.first_opentime)
                end
                dateStr = dateStr .. " " .. utc
                local messageBox = display.newMessageBox(string.format(L("ServerWillOpenError"), dateStr),function()
                end)
                cc.Director:getInstance():getRunningScene():addChild(messageBox, 1000)
                return
            end
        end
    
        if zoneData.status and zoneData.status == Enums.ServerStatus.Maintain then
            local messageBox = display.newMessageBox(L("tips_3000407"),function()
            end)
            cc.Director:getInstance():getRunningScene():addChild(messageBox, 1000)
            return
        end

        self._cacheZoneData = nil
        self._cacheGameLoginCb = nil
        
        local url = self:_joinUrl(zoneData.gatehost)
        app.session:login(url, nil, cb)
    end, 1, nil, nil, zoneData.utc, zoneData.id)
end

function ChannelEmaOversea:loginCallback(jsonStr)
    print("===================+>>>> loginCallback")
    local obj = json.decode(jsonStr)
    if obj then
        if obj.errCode == nil then
            self._loginParams = obj
            release_print("================>> sdklogin success")
            assert(self._loginParams.account ~= nil, "self._loginParams.account is nil, " .. jsonStr)
            --更新 时间
            self:updateSdkTimeDiff()
            self:hideLoginView()
            self:_onLoginSuccess()
        else
            self:_onLoginFail(obj.errCode)
        end
    else
        self:_onLoginFail("unknown error")
    end
end


function ChannelEmaOversea:_converServerFormat(p)
    local serverAddr = ""
    if p.socket_port2 and p.socket_port2 ~= "" then
        serverAddr = string.format("https://%s:%s/", p.socket_domain2, p.socket_port2)
    else
        serverAddr =  string.format("https://%s/", p.socket_domain2)
    end

    local gatehost = ""
    if p.server_port2 and p.server_port2 ~= "" then
        gatehost = string.format("https://%s:%s/", p.server_url2, p.server_port2)
    else
        gatehost =  string.format("https://%s/", p.server_url2)
    end

    -- gatehost = "http://10.246.89.230:28088/"
    -- serverAddr = "http://10.246.89.230:28877"
    --- 判读端口
    return {
        id = tonumber(p.server_id),
        name = tostring(p.server_name),
        addr = serverAddr,
        status = tostring(p.status or 1),
        first_opentime = math.floor( tonumber(p.first_opentime or "0") or 0 ),
        utc = p.utc,
        gatehost = gatehost
    }
end


function ChannelEmaOversea:newServersCallback(jsonStr)
    print("=====>>> newServersCallback ", jsonStr)
    if jsonStr == "fail" then
        local messageBox = display.newConfirmDialog(L("NetworkErrorWithRetry"),function()
            self:fetchNewServers()
        end)
        cc.Director:getInstance():getRunningScene():addChild(messageBox, 1000)
    else
        local obj = json.decode(jsonStr)
        if obj and #obj >= 1 then
            -- local newServers = {}
            local rServer = self:_converServerFormat(obj[1])
            if self._fetchListCallBack then
                self._fetchListCallBack({}, rServer)
                self._fetchListCallBack = nil
            end
        else
            -- if self._fetchListCallBack then
            --     self._fetchListCallBack({}, nil)
            --     self._fetchListCallBack = nil
            -- end
            self:fetchServerListByPageNum(nil, 1, nil, nil, "99")
        end
    end
   
end

function ChannelEmaOversea:myServersCallback(jsonStr)
    if jsonStr == "fail" then
        local messageBox = display.newConfirmDialog(L("NetworkErrorWithRetry"),function()
            self:fetchMyServers()
        end)
        cc.Director:getInstance():getRunningScene():addChild(messageBox, 1000)
    else
        local obj = json.decode(jsonStr)
        local tempServerMap = {}
        if obj then
            local myServers = {}
            for k, v in ipairs(obj) do
                local d = {}
               
                d.server = self:_converServerFormat(v)
                if tempServerMap[d.server.id] == nil then
                    tempServerMap[d.server.id] = true
                    table.insert(myServers, d)
                end
            end
            -- self._tempMyServers = myServers
            if #myServers == 0 then
                self:fetchNewServers()
            else
                if self._fetchListCallBack then
                    self._fetchListCallBack(myServers, {})
                    self._fetchListCallBack = nil
                end
            end
        end
    end
end

function ChannelEmaOversea:fetchServersCallback(jsonStr)
    print("=====>>> fetchServersCallback ", jsonStr)
    if jsonStr == "fail" then
        if self._fetchListCallBack then
            local messageBox = display.newConfirmDialog(L("NetworkErrorWithRetry"),function()
                self:fetchServerListByPageNum(nil, 1, nil, nil, "99")
            end)
            cc.Director:getInstance():getRunningScene():addChild(messageBox, 1000)
        elseif self._fetchSingleServerListByServerIdCb and self._cacheZoneData and self._cacheGameLoginCb then
            local messageBox = display.newConfirmDialog(L("NetworkErrorWithRetry"),function()
                self:gameLogin(self._cacheGameLoginCb, self._cacheZoneData)
            end)
            cc.Director:getInstance():getRunningScene():addChild(messageBox, 1000)
        end
        self._fetchServerListByPageNumCb = nil
    else
        local obj = json.decode(jsonStr)
        if obj then
            if self._fetchSingleServerListByServerIdCb then
                self._fetchSingleServerListByServerIdCb(obj)
                self._fetchSingleServerListByServerIdCb = nil
            elseif self._fetchReviewServerList then
                local servers = {}
                for k, v in ipairs(obj.data) do
                    local d = {}
                    d.server = self:_converServerFormat(v)
                    table.insert(servers, d)
                    break
                end 
                if #servers ~= 1 then
                    self._fetchListCallBack = self._fetchReviewServerList
                    self._fetchReviewServerList = nil
                    self:fetchMyServers()
                    -- local messageBox = display.newConfirmDialog("can not find review server, retry?",function()
                    --     self:fetchReviewServerList()
                    -- end)
                    -- cc.Director:getInstance():getRunningScene():addChild(messageBox, 1000)
                else
                    self._fetchReviewServerList(servers, {})
                    self._fetchReviewServerList = nil
                end
            elseif self._fetchListCallBack then
                -- 但推荐服没有获取到 就 拉去区服列表  获取第一个数据
                if obj.data and #obj.data > 0 then
                    local rServer  = self:_converServerFormat(obj.data[1])
                    if self._fetchListCallBack then
                        self._fetchListCallBack({}, rServer)
                        self._fetchListCallBack = nil
                    end
                else
                    if self._fetchListCallBack then
                        self._fetchListCallBack({}, nil)
                        self._fetchListCallBack = nil
                    end
                end
            else
                local servers = {}
                for k, v in ipairs(obj.data) do
                    table.insert(servers, self:_converServerFormat(v))
                end
                local d = {}
                d.servers = servers
                if self._fetchServerListByPageNumCb then
                    self._fetchServerListByPageNumCb(d , nil, tonumber(obj.count))
                    self._fetchServerListByPageNumCb = nil
                end

            end
        end
    end
    
end


function ChannelEmaOversea:switchAccoutCallback()
    release_print("======>>>> switchAccoutCallback")
    self._loginParams = {}
    app.session:clearLogined()
    self:_onLogoutSuccess()
end

function ChannelEmaOversea:getSdkTime()
    if self._tempCurTime == 0 then
        self:updateSdkTimeDiff()
        return 0
    end
    local curTime = os.time()

    return curTime + self._timeDt
end


function ChannelEmaOversea:updateSdkTimeDiff()
    self._tempCurTime = os.time()
    if app:isAndroid() then
        self.callJava("()V", "getTime")
    elseif app:isIOS() then
        self.callOC("getTime")
    end
end

function ChannelEmaOversea:payCallback(ret)
    local code = tonumber(ret)
    release_print("=====>> pay call back ret "..(ret or ""))
    if code == Enums.PayRetState.success then
        self:_onPaySuccess()
    else
        if app:isAndroid() then
            if code == 40002 then
                code = Enums.PayRetState.cancel
            else
                code = Enums.PayRetState.fail
            end
        elseif app:isIOS() then
            if code == 401002 then
                code = Enums.PayRetState.cancel
            else
                code = Enums.PayRetState.fail
            end
        end
        self:_onPayFail(code)
    end
end


function ChannelEmaOversea:showLoginView()
	if not self._view then
		local view = require("app.login.views.EmaOverseaLoginView").new()
		cc.Director:getInstance():getRunningScene():addChild(view, 1000)
		self._view = view
		view:onOperate(function(op, sender)
            if op == "emaOversea" then
                if self._loginCallback then
                    self:login(self._loginCallback)
                end
			end
			sender:enableButtons(false)
		end)
	end
	self._view:setVisible(true)
	self._view:enableButtons(true)
end

function ChannelEmaOversea:hideLoginView()
	if self._view then
		self._view:removeFromParent()
		self._view = nil
	end
end

-- 如果 init 返回速度快 的 话  这个回调 可能调用不到 
-- 需要主动 获取initstate
-- 这个 回调 主要是解决 网络延迟 loading结束还初始化好
-- function ChannelEmaOversea:initCallback(ret)
    -- if ret == "fail" then
    --     self._initSdkState = 1
    --     if app.channelAPI:checkIsNeedPopFirstRealName() then
    --         local msg = L("InitSdkFail")
    --         local messageBox = display.newMessageBox(msg,function()
                
    --         end)
    --         cc.Director:getInstance():getRunningScene():addChild(messageBox, 1000)
    --     end
    -- elseif ret == "success" then
    --     self._initSdkState = 0
    --     if self._isCallLogin then
    --         print("====>>>> init delay ")
    --         self:login()
    --     end
    -- end
-- end

-- 返回  0 表示 初始化成功
-- function ChannelEmaOversea:checkInitState()
    -- if self._initSdkState == -1 then
    --     local ok, ret
    --     if app:isAndroid() then
    --         ok, ret = self.callJava("()I", "getInitState")
    --     elseif app:isIOS() then
    --         ok, ret = self.callOC("getInitState")
    --     end
    --     self._initSdkState = ret
    -- end
    -- return self._initSdkState == 0
-- end


function ChannelEmaOversea:accountUpgradeCallback(param)
    if param == "success" then
        UIHandler:removeDesktopFunctionId(Constant.FUNC_TYPE_OVERSEA_ACCOUNT_UYPGRADE)
    end
end

function ChannelEmaOversea:forceLogoutCallback()
    local msg = L("ForceLogoutAccount")
    local messageBox = display.newMessageBox(msg,function()
        app:relaunchApp()
    end)
    cc.Director:getInstance():getRunningScene():addChild(messageBox, 1000)
end

function ChannelEmaOversea:_onGetProductListSuccess(dataArr)
    -- print("===========+>>>  _onGetProductListSuccess")
    -- dump(dataArr)
    self._goodsMap = {}
    for k, v in pairs(dataArr or {}) do
        self._goodsMap[v["productId"]] = v
    end

    app.session:request("pb_recharge.C2S_QueryRechargeGoods", {}, function(ret)
        if not ret then
            self:_onGetProductListFail()
            return 
        end
        local data = {}
        local goods = self:_clonePayGoodsInfo(ret.RechargeGoodsInfos)
       
        local fixGoods = {}
        for k, v in pairs(goods) do
            local product_id = v["product_id"]
            if self._goodsMap[product_id] then
                v.price = self._goodsMap[product_id].price
                table.insert(fixGoods, v)
            else
                release_print("can not find product_id ", product_id)
            end
        end
        data.RechargeGoodsInfos = fixGoods
        if self._getPayGoods then
            self._getPayGoods("success", data)
        end
    end)

end

function ChannelEmaOversea:_onGetProductListFail(code, error)
    release_print("============+>>>  get product list fail")
    if code == 2 then
        release_print("=============>> sdk close pay")
        self._sdkCanPay = false
    end
    if self._getPayGoods then
        self._getPayGoods("fail")
    end
    self._getPayGoods = nil
    -- display.pushToast(L("GetProductListFail"))
end

function ChannelEmaOversea:getProductListCallback(jsonStr)
    print("===========+>>>  getProductListCallback")
    local obj = json.decode(jsonStr)
    if obj then
        if obj.err then
            self:_onGetProductListFail(obj.ret, obj.code, obj.err)
        else
            self:_onGetProductListSuccess(obj.data)
        end
    else
        self:_onGetProductListFail(-1, "parse json fail")
    end
end

-- 获取商品列表
function ChannelEmaOversea:getPayGoods(cb)
    self._getPayGoods = cb
    if app:isAndroid() then
        self.callJava("()V", "getProductList")
    elseif app:isIOS() then
        self.callOC("getProductList")
    end
end


function ChannelEmaOversea:accountUpgrade()

end

-- function ChannelEmaOversea:checkGiftCode(giftCode)
--     local params = {
--         server_id = tostring(app.session:getZoneId()),
--         role_id = UD.player.uid,
--         gift_code = giftCode,
--     }
--     if app:isAndroid() then
--         local jstr = json.encode(params)
--         self.callJava("(Ljava/lang/String;)V", "checkGiftCode", jstr)
--     elseif app:isIOS() then
--         self.callOC("checkGiftCode", params)
--     end
-- end

-- function ChannelEmaOversea:checkGiftCodeCallback(param)
--     local num = tonumber(param)
--     if num == 0 then
--         display.pushToast(L("giftCodeSuccess"))
--     elseif num == 301 then
--         display.pushToast(L("giftCodeNotFind"))
--     elseif num == 302 then
--         display.pushToast(L("giftCodeInvalid"))
--     elseif num == 303 then
--         display.pushToast(L("giftCodeAlreadyUse"))
--     elseif num == 310 then
--         display.pushToast(L("giftCodeLoginStateInvalid"))
--     else
--         display.pushToast(L("giftCodeUnknowErr"))
--     end
-- end

function ChannelEmaOversea:reqGiftCode(code, cb)
    release_print("=============+>>> ", self:getOpId(), code)
    app.session:request("pb_recharge.C2S_UseGiftCode", {op_id = self:getOpId(), giftCode = code}, function(ret)
        if cb then
            cb(ret)
        end
    end)
end

function ChannelEmaOversea:reportConnectServer()
    if app:isAndroid() then
        self.callJava("(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", "connectServer", tostring(app.session:getZoneId()), UD.player.uid or "", UD.player.name or "")
    elseif app:isIOS() then
        local params = {
            server_id = tostring(app.session:getZoneId()),
            role_id = UD.player.uid or "",
            role_name = UD.player.name  or "",
        }
        self.callOC("connectServer", params)
    end
end


function ChannelEmaOversea:isReview()
    local ok, ret
    ret = false
    if app:isIOS() then
        ok, ret = self.callOC("isReview")
    end
    return ret
end

function ChannelEmaOversea:openSupport()
    if app:isAndroid() then
        self.callJava("(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", "openSupport", tostring(app.session:getZoneId()), tostring(UD.player.uid) or "", UD.player.name or "", UD.zoneName or "")
    elseif app:isIOS() then
        local params = {
            server_id = tostring(app.session:getZoneId()),
            role_id = tostring(UD.player.uid) or "",
            role_name = UD.player.name  or "",
            server_name = UD.zoneName or ""
        }
        self.callOC("openSupport", params)
    end
end


function ChannelEmaOversea:openGuestUpgrade()
    if app:isAndroid() then
        self.callJava("(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", "openGuestUpgrade", tostring(app.session:getZoneId()), UD.player.uid or "", UD.player.name or "", UD.zoneName or "")
    elseif app:isIOS() then
        local params = {
            server_id = tostring(app.session:getZoneId()),
            role_id = tostring(UD.player.uid) or "",
            role_name = UD.player.name  or "",
            custom_data = UD.zoneName or ""
        }
        self.callOC("openGuestUpgrade", params)
    end

end

function ChannelEmaOversea:isGuest()
    local ok, ret
    ret = false
    if app:isAndroid() then
        ok, ret = self.callJava("()Z", "isGuest")
    elseif app:isIOS() then
        ok, ret = self.callOC("isGuest")
    end
    return ret
end

function ChannelEmaOversea:jumpToAppShop()
    if app:isAndroid() then
        self.callJava("()V", "jumpToAppShop")
    elseif app:isIOS() then
        self.callOC("jumpToAppShop")
    end

end

--

function ChannelEmaOversea:ADReport(params)
    if not params then
        return
    end
    if app:isAndroid() then
        local channels = {
            "firebase",
            "facebook",
            "appsflyer",
            "adjust"
        }
        local stringChannel = {}
        for k, v in pairs(params.channels) do
            table.insert(stringChannel, channels[v])
        end
        params.channels = stringChannel
        local jstr = json.encode(params)
        self.callJava("(Ljava/lang/String;)V", "ADReport", jstr)
    elseif app:isIOS() then
        local channels = {
            "Google",
            "Facebook",
            "AppsFlyer",
            "Adjust"
        }
        local stringChannel = {}
        for k, v in pairs(params.channels) do
            table.insert(stringChannel, channels[v])
        end
        params.channels = stringChannel
        local jstr = json.encode(params)
        self.callOC("ADReport", {jsonStr = jstr})
    end

end

function ChannelEmaOversea:activeBuriedPointReport(params)
    if not params then
        return
    end
    if app:isAndroid() then
        local channels = {
            "firebase",
            "facebook",
            "appsflyer",
            "adjust"
        }
        local stringChannel = {}
        for k, v in pairs(params.channels) do
            table.insert(stringChannel, channels[v])
        end
        params.channels = stringChannel
        local jstr = json.encode(params)
        self.callJava("(Ljava/lang/String;)V", "activeBuriedPointReport", jstr)
    elseif app:isIOS() then
        local channels = {
            "Google",
            "Facebook",
            "AppsFlyer",
            "Adjust"
        }
        local stringChannel = {}
        for k, v in pairs(params.channels) do
            table.insert(stringChannel, channels[v])
        end
        params.channels = stringChannel
        local jstr = json.encode(params)
        self.callOC("activeBuriedPointReport", {jsonStr = jstr})
    end
end

function ChannelEmaOversea:deletePushData()
    if app:isAndroid() then
        self.callJava("()V", "deletePushData")
    elseif app:isIOS() then
        self.callOC("deletePushData")
    end
end


-- 推送 
--[[
    time 时间
    msg 消息
    title 推送标题
    UTC 时区 （int值  北京时区(utc8) 8  美国时区  -5 ）
    dataType int值 1为每天推送，每次保存14天内容，2为每周推送只保存2周内容，其他为显示一次
    className 推送点击之后需要打开的游戏启动Activity的路径名（com.emagroups.ea）
    pushType Android平台特有参数，类型ID，用来区分不同的推送内容。相同pushType的推送会相互覆盖
]]
function ChannelEmaOversea:savePushData(params)
    if not params then
        return
    end
    if app:isAndroid() then
        local jsonStr = json.encode(params)
        self.callJava("(Ljava/lang/String;)V", "savePushData", jsonStr)
    elseif app:isIOS() then
        self.callOC("savePushData", params)
    end
    
end

function ChannelEmaOversea:getDeviceId()
    local ok, ret
    if app:isAndroid() then
        ok, ret = self.callJava("()Ljava/lang/String;", "getDeviceId")
    elseif app:isIOS() then
        ok, ret = self.callOC("getDeviceId")
    end
    -- print("==========>>> getDeviceId ", ret)
    if ok then
        return ret
    end
    return ""
end


function ChannelEmaOversea:getClientIp()
    local ok, ret
    if app:isAndroid() then
        ok, ret = self.callJava("()Ljava/lang/String;", "getClientIp")
    elseif app:isIOS() then
        ok, ret = self.callOC("getClientIp")
    end
    if ok then
        return ret
    end
    return ""
end


function ChannelEmaOversea:getGameServerStatus()
    local ok, ret
    if app:isAndroid() then
        ok, ret = self.callJava("()Ljava/lang/String;", "getStatus")
    elseif app:isIOS() then
        ok, ret = self.callOC("getStatus")
    end
    if ok then
        return ret
    end
    return "-1"
end


return ChannelEmaOversea
